package com.biaobiaoqi.scoreanalysis.action;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;

public class validateCode extends ActionSupport {
	private static final long serialVersionUID = -6175441509851765024L;

	@SuppressWarnings("restriction")
	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = ServletActionContext.getRequest().getSession();
		response.setHeader("Cache-Control", "no-cache");
		int width = 50;
		int height = 25;
		BufferedImage image = new BufferedImage(width, height, 1);
		Graphics graphics = image.createGraphics();
		graphics.setColor(getColor());
		graphics.fillRect(0, 0, width, height);
		graphics.setFont(new Font("Arial", 1, 18));
		graphics.setColor(getColor());
		String number = String
				.valueOf(System.currentTimeMillis() % 9000L + 1000L);
		session.setAttribute("validateCode", number);
		graphics.drawString(number, (int) (width * 0.1D), (int) (height * 0.8D));
		graphics.dispose();
 		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response
				.getOutputStream());
		encoder.encode(image);
		response.getOutputStream().flush();
		response.getOutputStream().close();
		return null;
	}

	private Color getColor() {
		int red = (int) (Math.random() * 1000.0D % 256.0D);
		int green = (int) (Math.random() * 1000.0D % 256.0D);
		int blue = (int) (Math.random() * 1000.0D % 256.0D);
		return new Color(red, green, blue);
	}
}
